import { defineStore } from 'pinia'
import { io, Socket } from 'socket.io-client'
import { ref, onMounted } from 'vue'
import { useUser } from './useUser.js'
import { useMsg } from './useMsg.js'
import { ElNotification } from 'element-plus'


// 从环境变量获取 Socket URL
const SOCKET_URL = import.meta.env.VITE_SOCKET_URL
const RECONNECT_INTERVAL = 10000
const MAX_RECONNECT_ATTEMPTS = 20

export const useSocketStore = defineStore('socket', () => {
    const socket = ref<Socket | null>(null)
    const isConnected = ref(false)
    const reconnectAttempts = ref(0)
    const reconnectTimer = ref<number | null>(null)

    function initSocket() {
        if (socket.value) return
        const userStore = useUser()
        if (!userStore.getUserInfo || !userStore.getUserInfo.uimKey) return
        socket.value = io(SOCKET_URL, {
            query: {
                imKey: userStore.getUserInfo.uimKey
            },
            autoConnect: true,
            reconnection: true,
            reconnectionAttempts: MAX_RECONNECT_ATTEMPTS,
            reconnectionDelay: RECONNECT_INTERVAL,
            timeout: 10000,
            transports: ['websocket'],
        })

        setupSocketListeners()
    }

    function setupSocketListeners() {
        if (!socket.value) return

        socket.value.on('connect', () => {
            console.log('Socket connected')
            isConnected.value = true
            reconnectAttempts.value = 0
            clearReconnectTimer()
            // 获取聊天列表
            emit('chatList', {}, (res) => {
                if (res.code === 200) {
                    const msgStore = useMsg()
                    msgStore.setTalkList(res.data)
                }
            })
        })

        socket.value.on('disconnect', () => {
            console.log('Socket disconnected')
            isConnected.value = false
            startReconnectTimer()
        })

        socket.value.on('connect_error', (error) => {
            console.error('Connection error:', error)
            isConnected.value = false
            startReconnectTimer()
        })
        socket.value.on('chatMsg', (res) => {
            console.log('chatMsg:', res)
            if (window.location.href.indexOf('/message') === -1) {
                ElNotification.info({
                    title: `${res.data.msg.fromName}`,
                    message: lastMsg(res.data.msg),
                    onClick: () => {
                        window.location.href = '/#/message'
                    }
                })
                const msgStore = useMsg()
                msgStore.setMsgAudioStatus(true)
                setTimeout(() => {
                    msgStore.setMsgAudioStatus(false)
                }, 1000)
                // msgStore.setMsgUnreadCount(msgStore.getMsgUnreadCount + 1)
            }
            const msgStore = useMsg()
            if (res.code === 200) {
                // 如果是客服消息，则不添加到聊天列表
                if (res.data.msg.fromType === 3) {
                    msgStore.addMessage(res.data.msg.from, res.data.msg)
                } else {
                    msgStore.addMessage(res.data.msg.from, res.data.msg)
                }
                msgStore.updateTalkListLastMsg(res.data, 2)
                // 如果当前imKey不等于消息来源imKey，声音提醒，并更新未读消息数量
                if (msgStore.getCurrentImKey !== res.data.user) {
                    msgStore.setTlakItemNoReadNum(res.data)
                }
            }
        })
        socket.value.on('setRead', (res) => {
            console.log('setRead res:', res)
            const msgStore = useMsg()
            msgStore.setAppointMsgRead(res.from, res.msgKeys)
        })
    }

    function lastMsg(msg: any) {
        if (!msg) {
            return "--";
        }
        const contentType = msg.contentType;
        if (contentType === 1) {
            return msg.content;
        }
        if (contentType === 2) {
            return "[图片]";
        }
        if (contentType === 4) {
            //return '新提示消息';
        }
        if (contentType === 5) {
            return "[视频]";
        }
        if (contentType === 6) {
            return "[文件]";
        }
        if (contentType === 7) {
            return "[加价申请]";
        }
        if (contentType === 8) {
            return "[分享服务]";
        }
        if (contentType === 10) {
            return "[邀请支付]";
        }
        return "";
    }

    function startReconnectTimer() {
        if (reconnectTimer.value) return

        reconnectTimer.value = window.setInterval(() => {
            if (isConnected.value) {
                clearReconnectTimer()
                return
            }

            if (reconnectAttempts.value >= MAX_RECONNECT_ATTEMPTS) {
                clearReconnectTimer()
                console.error('Max reconnection attempts reached')
                return
            }

            reconnectAttempts.value++
            console.log(`Attempting to reconnect... (${reconnectAttempts.value}/${MAX_RECONNECT_ATTEMPTS})`)
            connect()
        }, RECONNECT_INTERVAL)
    }

    function clearReconnectTimer() {
        if (reconnectTimer.value) {
            clearInterval(reconnectTimer.value)
            reconnectTimer.value = null
        }
    }

    function connect() {
        if (!socket.value) {
            initSocket()
        } else {
            socket.value.connect()
        }
    }

    function disconnect() {
        socket.value?.disconnect()
        clearReconnectTimer()
    }

    function emit<T>(event: string, data?: T, callback?: (data: T) => void) {
        if (!isConnected.value) {
            console.warn('Socket is not connected. Message queued.')
            connect()
            return
        }
        socket.value?.emit(event, data, callback)
    }

    function on<T>(event: string, callback: (data: T) => void) {
        socket.value?.on(event, callback)
    }

    function off<T>(event: string, callback: (data: T) => void) {
        socket.value?.off(event, callback)
    }

    return {
        socket,
        isConnected,
        connect,
        disconnect,
        emit,
        on,
        off,
        initSocket,
    }
})